//
//  NSThread+Runloop.m
//  Pods
//
//  Created by 刘彬 on 2017/3/22.
//
//

#import "NSThread+Runloop.h"

NSString *const WDThreadHaveLoopSource = @"WDThreadHaveLoopSource";

@implementation NSThread (Runloop)

- (void)wd_addLoopSource {
    
    // 已经有loopsource了
    if ([[self.threadDictionary objectForKey:WDThreadHaveLoopSource] boolValue]) {
        return ;
    }
    // 主线程不用添加source，子线程需要手动添加source，防止runloop不运行
    if ([NSThread mainThread] != [NSThread currentThread]) {
        [[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSRunLoopCommonModes];
    }
    
    //标记下
    [self.threadDictionary setObject:@(YES) forKey:WDThreadHaveLoopSource];
}

+ (void)wd_runloopBlockUntilCondition:(WDRunloopBreak (^)(void))condition timeOut:(NSTimeInterval)time {
    if (!condition) {
        return ;
    }
    
    // 先确保runloop非空
    [[NSThread currentThread] wd_addLoopSource];
    
    // 获取超时时间
    CFAbsoluteTime beginAt = CFAbsoluteTimeGetCurrent();
    CFAbsoluteTime endAt = 0.0f;
    // 如果超时时间设置的小于等于0则取一个将来很久的时间
    if (time <= 0.0f) {
        endAt = [[NSDate distantFuture] timeIntervalSince1970];
    } else {
        endAt = beginAt + time;
    }
    
    BOOL isBreak = NO;
    do {
        isBreak = condition();
        // 达成预设条件，跳出
        if (isBreak) {
            break ;
        }
        CFAbsoluteTime now = CFAbsoluteTimeGetCurrent();
        CFAbsoluteTime seconds = endAt - now;
        // 到达超时时间，跳出
        if (seconds <= 0.0f) {
            break ;
        }
        
        @autoreleasepool {
            if ([[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:seconds]]) {
                continue;
            }
        }
    }
    while (YES);
}

@end
